package org.gl.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Environment;

public class FileUtil {
	private String SDCardRoot;

	public FileUtil() {
		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			// 得到当前外部存储设备的目录
			SDCardRoot = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + File.separator;
		}
	}

	/**
	 * 检查一个文件是否存在
	 * @param fileSavePathName 文件绝对路径
	 * @param isCreate 如果不存在 是否创建
	 * @return
	 * @throws IOException
	 */
	public File checkFile(String fileSavePathName, boolean isCreate)
			throws IOException {
		if (fileSavePathName == null) {
			fileSavePathName = "/home/zyfgeliang/videoRes/oh.mp4";
			return null;
		}
		File file = new File(fileSavePathName);
		File dir = new File(file.getParent());
		if (!dir.exists() && isCreate) {
			boolean createNewFileResult = dir.mkdirs();
			if (!createNewFileResult) {
				System.err.println("Don`t create dir:" + dir.getAbsolutePath());
				return null;
			}
		}
		if (!file.exists() && isCreate) {
			boolean createNewFileResult = file.createNewFile();
			if (!createNewFileResult) {
				System.err.println("Don`t create file:"
						+ file.getAbsolutePath());
				return null;
			}
		}
		return file;
	}

	/**
	 * 在SD卡上创建文件
	 * 
	 * @throws IOException
	 */
	private void createFileInSDCard(File file) {
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/*
	 * public void copyFile(File fileDir,File newDir,String newName) { //fileDir
	 * 要复制文件文件 //newDir 存放位置 File newFile=new File(newDir,newName);
	 * //newFile创建保存路径上的一个空文件 //findName（fileDir）提取文件名 int i; try {
	 * FileOutputStream outS=new FileOutputStream(newFile); BufferedOutputStream
	 * bOS=new BufferedOutputStream(outS); FileInputStream inS=new
	 * FileInputStream(fileDir); BufferedInputStream bIS=new
	 * BufferedInputStream(inS); //把这个文件当作一个流用来输入 while((i=bIS.read())!=-1) {
	 * bOS.write(i); } bOS.close(); bIS.close(); } catch(Exception e) {
	 * e.printStackTrace(); }
	 * 
	 * }
	 */
	/**
	 * 复制单个文件
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf.txt
	 * @return boolean
	 */
	public void copyFile(String oldPath, String newPath) {
		try {
			int byteread = 0;

			if (newPath.equals(oldPath)) {
				return;
			}

			File oldfile = new File(oldPath);
			File newfile = new File(newPath.substring(0,
					newPath.lastIndexOf("/")));
			if (!newfile.exists()) {
				newfile.mkdir();
			}
			if (oldfile.exists()) { // 文件存在时
				FileInputStream inStream = new FileInputStream(oldPath); // 读入原文件
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					// System.out.println(bytesum);
					new FileOutputStream(newPath).write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println(" 复制单个文件操作出错");
			e.printStackTrace();

		}

	}

	public void writeToFile(String fileName, Map<String, String> msgContent,
			String sendAccout) {
		File file = new File(SDCardRoot + fileName + ".txt");
		createFileInSDCard(file);
		FileOutputStream outputStream = null;
		String instant_msg = msgContent.get("instant_msg_content");
		instant_msg = instant_msg.replaceAll("\r", " ");
		instant_msg = instant_msg.replaceAll("\n", " ");
		String content = sendAccout + ":" + instant_msg;

		try {
			outputStream = new FileOutputStream(file, true);
			outputStream.write(content.getBytes());
			outputStream.write("\r\n".getBytes());
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	public List<String> readFileByLines(String fileName) {
		File file = new File(SDCardRoot + fileName + ".txt");
		BufferedReader reader = null;
		List<String> lista = new ArrayList<String>();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				lista.add(tempString);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return lista;
	}

	public boolean delFile(String fileName) {
		File file = new File(SDCardRoot + fileName + ".txt");
		boolean d = false;
		if (file.exists()) {
			d = file.delete();
		}
		return d;
	}

	/***
	 * 删除路径下的所有文件
	 * **/

	public void delLogFileByUserid(String userid) {
		File file = new File(SDCardRoot);
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (tempList[i].startsWith(userid + "_")) {
				temp = new File(SDCardRoot + tempList[i]);
			}
			if (temp != null) {
				if (temp.isFile()) {
					temp.delete();
				}
			}
		}
	}

	/***
	 * 删除路径下的所有文件
	 * **/

	public void delLogFileByUCid(String userid, String conid) {
		File file = new File(SDCardRoot);
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (tempList[i].startsWith(userid + "_" + conid + "_")) {
				temp = new File(SDCardRoot + tempList[i]);
			}
			if (temp != null) {
				if (temp.isFile()) {
					temp.delete();
				}
			}
		}
	}

	private List<String> imagePaths = null;// 存放图片路径

	/**
	 * 得到sd卡目录下所有的图片路径
	 * 
	 * @author zhoubin
	 * **/
	public List<String> getAllPicturePath() {
		imagePaths = new ArrayList<String>();
		getPictureByPath(SDCardRoot);
		return imagePaths;
	}

	/**
	 * 检索路径下的图片
	 * 
	 * @author zhoubin
	 * **/
	public void getPictureByPath(String path) {
		File file = new File(path);
		String[] tempList = file.list();
		File temp = null;
		if (tempList != null) {
			for (int i = 0; i < tempList.length; i++) {
				temp = new File(path + tempList[i]);
				if (temp.isFile()) {// 是一个文件
					if (getMIMEType(tempList[i])) {// 是一个图片文件
						imagePaths.add(path + tempList[i]);
					}

				} else {// 是一个文件夹
					String fac = SDCardRoot;
					if (temp.getAbsolutePath().equals(fac)) {
						continue;
					}
					getPictureByPath(path + tempList[i] + File.separator);
				}
			}
		}
	}

	public String[] getFileNames(String userId, String imType, String logDate) {
		File file = new File(SDCardRoot);
		String[] fileList = file.list();
		String list[] = new String[fileList.length];
		int j = 0;
		String filePattern = userId + "_\\d" + "_" + imType + "_"
				+ logDate.replace("/", "").substring(0, 4) + ".txt";
		Pattern p = Pattern.compile(filePattern);
		for (int i = 0; i < fileList.length; i++) {

			Matcher m = p.matcher(fileList[i]);
			if (m.matches()) {
				lg.e("fileList[i]:", fileList[i] + "");
				list[j] = fileList[i];
				j++;
			}
		}
		return list;
	}

	/**
	 * 判断文件是否为图片
	 * 
	 * @author zhoubin
	 * **/
	private boolean getMIMEType(String fileName) {
		String end = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length()).toLowerCase();
		if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			return true;
		} else {
			return false;
		}
	}

	public List<String> getImagePaths() {
		return imagePaths;
	}

}
